﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using System.Threading.Tasks;
using LiveCharts;
using LiveCharts.Wpf;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using HIWSystem.Models;
using HIWSystem.Common;
using System.IO;
using System.Windows;
using System.Data;
using System.Windows.Media;

namespace HIWSystem.ViewModel
{
    public class IMDInfoEntryViewModel :ViewModelBase
    {
        public class LogEntity
        {
            public string Sn { get; set; }
            public string PN { get; set; }
            public string Station { get; set; }
            public string UL { get; set; }
            public string LL { get; set; }
            public string TestValue { get; set; }
            public string Result { get; set; }
            public string Actor { get; set; }
            public string Source { get; set; }
            public string CreateAt { get; set; }
        }
        #region 属性
        //测试PASS和Fail的数量
        int passCount = 0, failCount = 0;
        //用于判断是不是第一次触发过滤，是则备份原始数据源
        private bool isFirstFilterPN = true;
        private bool isFirstFilterStation = true;
       
        //用于再ComboBox控件中输入内容过滤时备份原始的数据源
        //当没有输入内容时恢复到备份的原始数据源
        ObservableCollection<PartNumberEntity> backupPNs = null;
        ObservableCollection<StationsEntity> backupStations = null;
        private ObservableCollection<PartNumberEntity> pns;
        private Dictionary<string, string> dicConfigFilesInfo = new Dictionary<string, string>();//IMD配置文件信息
        private ObservableCollection<LogEntity> IMDStationSpecConfigInfo = new ObservableCollection<LogEntity>();//IMD站位和指标配置信息

        /// <summary>
        /// 机种实体集合
        /// </summary>
        public ObservableCollection<PartNumberEntity> PNs
        {
            get { return pns; }
            set { pns = value; this.RaisePropertyChanged(() => PNs); }
        }
        private PartNumberEntity selectedPartNumber;
        /// <summary>
        /// 选择的机种实体
        /// </summary>
        public PartNumberEntity SelectedPartNumber
        {
            get { return selectedPartNumber; }
            set { selectedPartNumber = value; this.RaisePropertyChanged(() => SelectedPartNumber); }
        }
        private string pn;
        /// <summary>
        /// 机种
        /// </summary>
        public string PN
        {
            get { return pn; }
            set { pn = value; this.RaisePropertyChanged(() => PN); }
        }
        private bool isOpenComboPNDropDown;
        /// <summary>
        /// 是否展开机种下拉框选项卡
        /// </summary>
        public bool IsOpenComboPNDropDown
        {
            get { return isOpenComboPNDropDown; }
            set { isOpenComboPNDropDown = value; this.RaisePropertyChanged(() => IsOpenComboPNDropDown); }
        }
        private string searchPNText;
        /// <summary>
        /// 机种下拉框中输入的文本内容
        /// </summary>
        public string SearchPNText
        {
            get { return searchPNText; }
            set { searchPNText = value; this.RaisePropertyChanged(() => SearchPNText); }
        }
        private ObservableCollection<StationsEntity> stations;
        /// <summary>
        /// 站位信息
        /// </summary>
        public ObservableCollection<StationsEntity> Stations
        {
            get { return stations; }
            set { stations = value; this.RaisePropertyChanged(() => Stations); }
        }
        private string selectedStation;
        /// <summary>
        /// 选择的站位
        /// </summary>
        public string SelectedStation
        {
            get { return selectedStation; }
            set { selectedStation = value; this.RaisePropertyChanged(() => SelectedStation); }
        }
        private string station;
        /// <summary>
        /// 站位
        /// </summary>
        public string Station
        {
            get { return station; }
            set
            {
                station = value; this.RaisePropertyChanged(() => Station);
                this.IsVisibilityTestValue2 = Station.IndexOf('/') > -1 ? Visibility.Visible : Visibility.Hidden;
            }
        }
        private bool isOpenComboStationDropDown;
        /// <summary>
        /// 是否展开站位下拉列表框
        /// </summary>
        public bool IsOpenComboStationDropDown
        {
            get { return isOpenComboStationDropDown; }
            set { isOpenComboStationDropDown = value; this.RaisePropertyChanged(() => IsOpenComboStationDropDown); }
        }
        private string searchStationText;
        /// <summary>
        ///  站位下拉列表框搜索的文本
        /// </summary>
        public string SearchStationText
        {
            get { return searchStationText; }
            set { searchStationText = value; this.RaisePropertyChanged(() => SearchStationText); }
        }
        private string ul;
        /// <summary>
        /// 指标上限
        /// </summary>
        public string UL
        {
            get { return ul; }
            set { ul = value; this.RaisePropertyChanged(() => UL); }
        }
        private string ll;
        /// <summary>
        /// 指标下限
        /// </summary>
        public string LL
        {
            get { return ll; }
            set { ll = value; this.RaisePropertyChanged(() => LL); }
        }
        private string sn;
        /// <summary>
        /// 序列号信息
        /// </summary>
        public string SN
        {
            get { return sn; }
            set { sn = value; this.RaisePropertyChanged(() => SN); }
        }
        private bool isFocusSn=true;
        /// <summary>
        /// 是否聚焦条码框
        /// </summary>
        public bool IsFocusSn
        {
            get { return isFocusSn; }
            set { isFocusSn= value; this.RaisePropertyChanged(() => IsFocusSn); }
        }
        private bool isFocusTestValue1=false;
        /// <summary>
        /// 是否聚焦测试值1文本框
        /// </summary>
        public bool IsFocusTestValue1
        {
            get { return isFocusTestValue1; }
            set { isFocusTestValue1 = value; this.RaisePropertyChanged(() => IsFocusTestValue1); }
        }
        private bool isFocusTestValue2 = false;
        /// <summary>
        /// 是否聚焦测试值1文本框
        /// </summary>
        public bool IsFocusTestValue2
        {
            get { return isFocusTestValue2; }
            set { isFocusTestValue2 = value; this.RaisePropertyChanged(() => IsFocusTestValue2); }
        }
        private string testValue1;
        /// <summary>
        /// 测试的值
        /// </summary>
        public string TestValue1
        {
            get { return testValue1; }
            set { testValue1 = value; this.RaisePropertyChanged(() => TestValue1); }
        }
        private string testValue2;
        /// <summary>
        /// 测试值2
        /// </summary>
        public string TestValue2
        {
            get { return testValue2; }
            set { testValue2 = value; this.RaisePropertyChanged(() => TestValue2); }
        }

        private ObservableCollection<LogEntity> logs;
        /// <summary>
        /// 测试流程
        /// </summary>
        public ObservableCollection<LogEntity> Logs
        {
            get { return logs; }
            set { logs = value; this.RaisePropertyChanged(() => Logs); }
        }
        private SeriesCollection pieSeriesCollection;
        /// <summary>
        /// 饼形图系列集合
        /// </summary>
        public SeriesCollection PieSeriesCollection
        {
            get { return pieSeriesCollection; }
            set { pieSeriesCollection = value; this.RaisePropertyChanged(() => PieSeriesCollection); }
        }
        private string source;
        /// <summary>
        /// 产品来源《新装、维修、OBA》
        /// </summary>
        public string Source
        {
            get { return source; }
            set { source = value; this.RaisePropertyChanged(() => Source); }
        }
        private Visibility isVisibilityTestValue2=Visibility.Hidden;
        /// <summary>
        /// 是否显示第二个测试值文本框
        /// </summary>
        public Visibility IsVisibilityTestValue2
        {
            get { return isVisibilityTestValue2; }
            set { isVisibilityTestValue2 = value; this.RaisePropertyChanged(() => IsVisibilityTestValue2); }
        }

        #endregion

        #region 命令
        private RelayCommand loadPageCmd;
        /// <summary>
        /// 页面加载命令
        /// </summary>
        public RelayCommand LoadPageCmd
        {
            get 
            {
                if (loadPageCmd==null)
                {
                    loadPageCmd = new RelayCommand(LoadPage);
                }
                return loadPageCmd; 
            }
            set { loadPageCmd = value; }
        }
        private RelayCommand filterPNCmd;
        /// <summary>
        /// 机种过滤
        /// </summary>
        public RelayCommand FilterPNCmd
        {
            get
            {
                if (filterPNCmd == null)
                {
                    filterPNCmd = new RelayCommand(FilterPN);
                }
                return filterPNCmd;
            }
            set { filterPNCmd = value; }
        }
        private RelayCommand filterStationCmd;

        public RelayCommand FilterStationCmd
        {
            get 
            {
                if (filterStationCmd==null)
                {
                    filterStationCmd = new RelayCommand(FilterStation);
                }
                return filterStationCmd; 
            }
            set { filterStationCmd = value; }
        }

        private RelayCommand<string> comboPN_SelectionChangedCmd;
        /// <summary>
        /// 机种下拉列表框选择改变事件
        /// </summary>
        public RelayCommand<string> ComboPN_SelectionChangedCmd
        {
            get
            {
                if (comboPN_SelectionChangedCmd == null)
                {
                    comboPN_SelectionChangedCmd = new RelayCommand<string>(ComboPN_SelectionChangedHandler);
                }
                return comboPN_SelectionChangedCmd;
            }
            set { comboPN_SelectionChangedCmd = value; }
        }
        private RelayCommand<string> comboStation_SelectionChangedCmd;

        public RelayCommand<string> ComboStation_SelectionChangedCmd
        {
            get 
            {
                if (comboStation_SelectionChangedCmd==null)
                {
                    comboStation_SelectionChangedCmd = new RelayCommand<string>(ComboStation_SelectionChangedHandler);
                }
                return comboStation_SelectionChangedCmd; 
            }
            set { comboStation_SelectionChangedCmd = value; }
        }
        private RelayCommand snKeyEnterCommand;

        public RelayCommand SNKeyEnterCommand
        {
            get 
            {
                if (snKeyEnterCommand==null)
                {
                    snKeyEnterCommand = new RelayCommand(SNKeyEnterHandler);
                }
                return snKeyEnterCommand; 
            }
            set { snKeyEnterCommand = value; }
        }
        private RelayCommand spec1KeyEnterCommand;

        public RelayCommand Spec1KeyEnterCommand
        {
            get 
            {
                if (spec1KeyEnterCommand==null)
                {
                    spec1KeyEnterCommand = new RelayCommand(SpecKeyEnterHandler);
                }
                return spec1KeyEnterCommand; 
            }
            set { spec1KeyEnterCommand = value; }
        }
        private RelayCommand spec2KeyEnterCommand;

        public RelayCommand Spec2KeyEnterCommand
        {
            get
            {
                if (spec2KeyEnterCommand == null)
                {
                    spec2KeyEnterCommand = new RelayCommand(Spec2KeyEnterHandler);
                }
                return spec2KeyEnterCommand;
            }
            set { spec2KeyEnterCommand = value; }
        }
        private RelayCommand entryCmd;

        public RelayCommand EntryCmd
        {
            get 
            {
                if (entryCmd==null)
                {
                    entryCmd = new RelayCommand(Entry);
                }
                return entryCmd; 
            }
            set { entryCmd = value; }
        }
        private RelayCommand<string> newAssemblyCmd;

        public RelayCommand<string> NewAssemblyCmd
        {
            get 
            {
                if (newAssemblyCmd==null)
                {
                    newAssemblyCmd = new RelayCommand<string>(SelectSource);
                }
                return newAssemblyCmd; 
            }
            set { newAssemblyCmd = value; }
        }
        private RelayCommand<string> repairCmd;

        public RelayCommand<string> RepairCmd
        {
            get 
            {
                if (repairCmd==null)
                {
                    repairCmd = new RelayCommand<string>(SelectSource);
                }
                return repairCmd; 
            }
            set { repairCmd = value; }
        }
        private RelayCommand<string> OBAcmd;

        public RelayCommand<string> OBACmd
        {
            get 
            {
                if (OBAcmd==null)
                {
                    OBAcmd = new RelayCommand<string>(SelectSource);
                }
                return OBAcmd; 
            }
            set { OBAcmd = value; }
        }
        #endregion


        #region 方法
        //页面加载
        private void LoadPage()
        {
            this.FillPNToComboBox();
        }
        //添加机种到下拉列表框中
        private void FillPNToComboBox()
        {
            int meetCount = 0; //列表中存在相同机种数量
            string tmpPN = string.Empty;//机种
            string[] PNFiles = Directory.GetFiles(Global.IMDEntryInfoConfigDirectory, "*.xml");
            PNs = new ObservableCollection<PartNumberEntity>();
            dicConfigFilesInfo = new Dictionary<string, string>();
            foreach (var pf in PNFiles)
            {
                tmpPN = pf.Substring(pf.LastIndexOf("\\") + 1).Split('.')[0];
                meetCount = PNs.Count(x => x.PN == tmpPN);
                if (meetCount == 0)
                {
                    PNs.Add(new PartNumberEntity { PN = tmpPN });
                    dicConfigFilesInfo.Add(tmpPN, pf);
                }
                   
            }
        }
        /// <summary>
        /// 筛选机种下拉列表框中的数据
        /// </summary>
        private void FilterPN()
        {

            IsOpenComboPNDropDown = true;
            //当是第一次过滤的时候备份原始数据
            //这样是为了当不输入搜索条件时添加原始数据到列表中
            //当输入搜索条件时生成过滤集合绑定当下拉列表中
            if (isFirstFilterPN)
            {
                backupPNs = new ObservableCollection<PartNumberEntity>();
                backupPNs = PNs;
                isFirstFilterPN = false;
            }
            if (!string.IsNullOrEmpty(SearchPNText))
            {
                IEnumerable<PartNumberEntity> partNumberEntities = PNs.Where(s => s.PN.ToUpper().Contains(SearchPNText.ToUpper()));
                PNs = new ObservableCollection<PartNumberEntity>();
                foreach (var p in partNumberEntities)
                {
                    PNs.Add(p);
                }
            }
            else
            {
                PNs = backupPNs;
            }

        }
        /// <summary>
        /// 筛选站位下拉列表框中的数据
        /// </summary>
        private void FilterStation()
        {
            IsOpenComboStationDropDown = true;
            //当是第一次过滤的时候备份原始数据
            //这样是为了当不输入搜索条件时添加原始数据到列表中
            //当输入搜索条件时生成过滤集合绑定当下拉列表中
            if (isFirstFilterStation)
            {
                backupStations = new ObservableCollection<StationsEntity>();
                backupStations = Stations;
                isFirstFilterStation = false;
            }
            if (!string.IsNullOrEmpty(SearchStationText) && Stations!=null)
            {
                IEnumerable<StationsEntity> stations = Stations.Where(s => s.Station.ToUpper().Contains(SearchStationText.ToUpper()));
                Stations = new ObservableCollection<StationsEntity>();
                foreach (var s in stations)
                {
                    Stations.Add(s);
                }
            }
            else
            {
                Stations = backupStations;
            }

        }
        /// <summary>
        /// 机种下拉框选项改变事件处理函数
        /// </summary>
        /// <param name="param">机种</param>
        private void ComboPN_SelectionChangedHandler(string param)
        {
            string path = string.Empty;//保存的路径
            string configStation = string.Empty;//配置文件中的站位信息
            string specUL = string.Empty, specLL = string.Empty;//指标的上限和下限
            bool isExists = false;//集合Stations中是否已经存在相同的站位信息
            if (param == null)
            {
                return;
            }
            //机种对应的完整路径信息
            path = dicConfigFilesInfo[param];
            XDocument xDoc = XDocument.Load(path);
            var staElement= xDoc.Element("EntryInfos").Element("EntryInfo").Element("Stations").Elements("Station");
            IMDStationSpecConfigInfo = new ObservableCollection<LogEntity>();
            foreach (var s in staElement)
            {
                isExists = false;
                try
                {
                    configStation = s.Attribute("Name").Value;//Name属性对应的值
                    specUL = s.Attribute("UL").Value;//UL属性对应的值
                    specLL = s.Attribute("LL").Value;//LL属性对应的值
                }
                catch (NullReferenceException)
                {
                    configStation = "";
                    specUL = "";
                    specLL = "";
                    MessageBox.Show(string.Format("机种【{0}】相关配置不完善，请先完善配置.", param),"软件温馨提示",MessageBoxButton.OK,MessageBoxImage.Error);
                }
               
                if (!string.IsNullOrEmpty(configStation) && !string.IsNullOrEmpty(specUL) && !string.IsNullOrEmpty(specLL))
                {
                   isExists= IMDStationSpecConfigInfo.Count(x => x.Station.ToUpper() == configStation.ToUpper()) > 0 ? true : false;
                    if (!isExists)
                    {
                        IMDStationSpecConfigInfo.Add(new LogEntity { Station = configStation, UL = specUL, LL = specLL });
                    }
                }
            }
        }
        /// <summary>
        /// 选择来源《新装、维修、OBA测试等...》
        /// </summary>
        /// <param name="source"></param>
        private void SelectSource(string source)
        {
            this.Source = source;
        }

        /// <summary>
        /// 站位下拉框选项改变事件处理函数
        /// </summary>
        /// <param name="obj">站位</param>
        private void ComboStation_SelectionChangedHandler(string obj)
        {
            string path = string.Empty;//保存路径
            string configUL = string.Empty;
            string configLL = string.Empty;
            if (obj==null)
            {
                return;
            }
            if (string.IsNullOrEmpty(this.PN))
            {
                MessageBox.Show("机种信息不能为空!","软件温馨提示",MessageBoxButton.OK,MessageBoxImage.Warning);
                return;
            }
            path = dicConfigFilesInfo[this.PN];
            XDocument xDoc =XDocument.Load(path);
            var staElements = xDoc.Element("EntryInfos").Element("EntryInfo").Element("Stations").Elements("Station").Where(x=>x.Attribute("Name").Value==obj);
            foreach (var s in staElements)
            {
                configUL = s.Attribute("UL").Value;
                configLL = s.Attribute("LL").Value;
                break;//如果配置了多个相同的站位则取第一个配置信息
            }
            //判断输入的指标是不是有效的
            if (!BusinessProcess.IsValidSpec(configUL))
            {
                MessageBox.Show("配置文件中,站位【"+obj+"】对应的上限指标【"+configUL+"】不是有效指标.\n请检查配置文件!", "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            this.UL = configUL; //填充指标上限到UI
            if (!BusinessProcess.IsValidSpec(configLL))
            {
                MessageBox.Show("配置文件中,站位【" + obj + "】对应的下限指标【" + configLL + "】不是有效指标.\n请检查配置文件!", "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            this.LL = configLL;//填充指标下限到UI
            this.UL = configUL;//填充指标上限到UI
        }
        /// <summary>
        /// 检查站位指标配置是否完善
        /// </summary>
        /// <param name="IMDStations">IMD站位集合</param>
        /// <param name="retMsg">返回的信息</param>
        /// <returns></returns>
        private bool CheckStationSpecConfigIsOk(string IMDStations,out string retMsg)
        {
            List<string> lstIMDStations = new List<string>();
            lstIMDStations = IMDStations.Split('/').ToList<string>();
            foreach (var s in lstIMDStations)
            {
                if (IMDStationSpecConfigInfo.Count(x => x.Station == "IMD"+s)<=0)
                {
                    retMsg = string.Format("机种【{0}】对应的站位【{1}】相关配置不完善，请先完善配置.",PN,s);
                    return false;
                } 
            }
            retMsg = "OK";
            return true;
        }
        private void Entry()
        {
            string startTime = string.Empty;
            int intTestValue = 0;
            int intUL = 0;
            int intLL = 0;
            string retMsg = string.Empty;//数据库返回的状态码和状态信息
            string[] arrayMsg = new string[2]; //截取返回的状态码和状态信息
            TrackingEntity trackingEntity = new TrackingEntity();
            DataTable dtTracking = new DataTable();
            if (string.IsNullOrEmpty(this.Source))
            {
                MessageBox.Show("来源信息不能为空.", "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            if (!CheckSnInfo())
                return;
            if (string.IsNullOrEmpty(Station))
            {
                MessageBox.Show("站位信息不能为空.", "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            string strCheck = string.Empty;
            if (!CheckStationSpecConfigIsOk(Station,out strCheck))
            {
                MessageBox.Show(strCheck, "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            //两个IMD工站信息
            if (IsVisibilityTestValue2 == Visibility.Visible)
            {
                if (string.IsNullOrEmpty(TestValue1) || string.IsNullOrEmpty(TestValue2))
                {
                    MessageBox.Show("测试值不能为空", "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                if (!CheckTestValue(TestValue1) || !CheckTestValue(TestValue2))
                    return;
                for (int i = 0; i < 2; i++)
                {
                    startTime = DateTime.Now.ToString();
                    if (i == 0)
                        intTestValue = Convert.ToInt32(TestValue1);
                    else
                        intTestValue = Convert.ToInt32(TestValue2);
                    
                    trackingEntity = new TrackingEntity();
                    trackingEntity.Sn = SN.ToUpper();
                    trackingEntity.Station ="IMD"+Station.Split('/').ElementAt(i);
                    intUL = Convert.ToInt32(IMDStationSpecConfigInfo.First(x => x.Station == trackingEntity.Station).UL);
                    intLL = Convert.ToInt32(IMDStationSpecConfigInfo.First(x => x.Station == trackingEntity.Station).LL);
                    if (intTestValue >= intLL && intTestValue <= intUL)
                        trackingEntity.Result = "PASS";
                    else
                        trackingEntity.Result = "FAIL";
                    trackingEntity.EquipmentName = Environment.MachineName;
                    trackingEntity.StartTime = startTime;
                    trackingEntity.StopTime = DateTime.Now.ToString();
                    trackingEntity.Actor = LogInInfo.User;
                    //trackingEntity.TunningInfo = new TunningEntity { Source = this.Source };
                    trackingEntity.IMDInfo = new IMDEntity { Source = this.Source, TestValue = intTestValue.ToString(), UpperLimit = intUL.ToString(), LowerLimit = intLL.ToString() };
                    retMsg = BusinessProcess.AddEndTracking(trackingEntity, out dtTracking);
                    arrayMsg = retMsg.Split('|');
                    if (arrayMsg[0] == "OK")
                    {
                        //首次添加要初始化Log集合
                        if (Logs == null)
                            Logs = new ObservableCollection<LogEntity>();
                        Logs.Add(new LogEntity
                        {
                            Sn = this.SN.ToUpper() ?? "",
                            PN = this.PN.ToUpper() ?? "",
                            Station = trackingEntity.Station ?? "",
                            UL = intUL.ToString() ?? "",
                            LL = intLL.ToString() ?? "",
                            TestValue = intTestValue.ToString()?? "",
                            Result = trackingEntity.Result,
                            Actor = LogInInfo.User,
                            Source = this.Source,
                            CreateAt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                        });
                        //根据时间进行降序排序，便于将最近一条记录显示再最上面。
                        var a = Logs.OrderByDescending(x => Convert.ToDateTime(x.CreateAt)).ToList();
                        Logs = new ObservableCollection<LogEntity>();
                        for (int j= 0; j < a.Count; j++)
                        {
                            Logs.Add(new LogEntity
                            {
                                Sn = a[j].Sn ?? "",
                                PN = a[j].PN ?? "",
                                Station = a[j].Station ?? "",
                                UL=a[j].UL??"",
                                LL = a[j].LL ?? "",
                                TestValue=a[j].TestValue ??"",
                                Result = a[j].Result ?? "",
                                Actor = a[j].Actor ?? "",
                                Source=a[j].Source??"",
                                CreateAt = a[j].CreateAt ?? "",
                            });
                        }
                        if (i==1)
                        {
                            this.SN = "";
                            this.TestValue1 = "";
                            this.TestValue2 = "";
                            this.IsFocusSn = true;
                            this.IsFocusTestValue1 = false;
                        }
                        if (trackingEntity.Result == "PASS")
                        {
                            passCount += 1;
                        }
                        else
                        {
                            failCount += 1;
                        }
                        this.AddPieSeriesData();//刷新饼形图
                    }
                    else
                    {
                        MessageBox.Show(arrayMsg[1], "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }
            //单个IMD站位信息录入
            else
            {
                if (string.IsNullOrEmpty(TestValue1))
                {
                    MessageBox.Show("测试值不能为空", "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                if (!CheckTestValue(TestValue1))
                    return;
                intTestValue = Convert.ToInt32(this.TestValue1);
                //intUL = Convert.ToInt32(this.UL);
                //intLL = Convert.ToInt32(this.LL);
                startTime = DateTime.Now.ToString();
                trackingEntity.Sn = this.SN.ToUpper();
                trackingEntity.Station ="IMD"+ this.Station.ToUpper();
                intUL = Convert.ToInt32(IMDStationSpecConfigInfo.First(x => x.Station == trackingEntity.Station).UL);
                intLL = Convert.ToInt32(IMDStationSpecConfigInfo.First(x => x.Station == trackingEntity.Station).LL);
                if (intTestValue > intLL && intTestValue < intUL)
                    trackingEntity.Result = "PASS";
                else
                    trackingEntity.Result = "FAIL";
                trackingEntity.EquipmentName = Environment.MachineName;
                trackingEntity.StartTime = startTime;
                trackingEntity.StopTime = DateTime.Now.ToString();
                trackingEntity.Actor = LogInInfo.User;
                trackingEntity.IMDInfo = new IMDEntity { Source = this.Source, TestValue = intTestValue.ToString(),UpperLimit=intUL.ToString(),LowerLimit=intLL.ToString() };
                // trackingEntity.TunningInfo = new TunningEntity { Source = this.Source };
                //trackingEntity.TunningInfo.Source = this.Source;
                //retMsg = "OK|插入成功!"; --用于调试使用
                retMsg = BusinessProcess.AddEndTracking(trackingEntity, out dtTracking);
                arrayMsg = retMsg.Split('|');
                if (arrayMsg[0] == "OK")
                {
                    //首次添加要初始化Log集合
                    if (Logs == null)
                        Logs = new ObservableCollection<LogEntity>();
                    Logs.Add(new LogEntity
                    {
                        Sn = this.SN.ToUpper() ?? "",
                        PN = this.PN.ToUpper() ?? "",
                        Station = trackingEntity.Station ?? "",
                        UL = intUL.ToString() ?? "",
                        LL = intLL.ToString() ?? "",
                        TestValue = this.TestValue1 ?? "",
                        Result = trackingEntity.Result,
                        Actor = LogInInfo.User,
                        Source = this.Source,
                        CreateAt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                    });
                    //根据时间进行降序排序，便于将最近一条记录显示再最上面。
                    var a = Logs.OrderByDescending(x => Convert.ToDateTime(x.CreateAt)).ToList();
                    Logs = new ObservableCollection<LogEntity>();
                    for (int j = 0; j < a.Count; j++)
                    {
                        Logs.Add(new LogEntity
                        {
                            Sn = a[j].Sn ?? "",
                            PN = a[j].PN ?? "",
                            Station = a[j].Station ?? "",
                            UL = a[j].UL ?? "",
                            LL = a[j].LL ?? "",
                            TestValue = a[j].TestValue ?? "",
                            Result = a[j].Result ?? "",
                            Actor = a[j].Actor ?? "",
                            Source = a[j].Source ?? "",
                            CreateAt = a[j].CreateAt ?? "",
                        });
                    }
                    this.SN = "";
                    this.TestValue1 = "";
                    this.TestValue2 = "";
                    this.IsFocusSn = true;
                    this.IsFocusTestValue1 = false;
                    if (trackingEntity.Result == "PASS")
                    {
                        passCount += 1;
                    }
                    else
                    {
                        failCount += 1;
                    }
                    this.AddPieSeriesData();//刷新饼形图
                }
                else
                {
                    MessageBox.Show(arrayMsg[1], "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            
        }

        /// <summary>
        /// 序列号回车事件处理
        /// </summary>
        private void SNKeyEnterHandler()
        {
            bool isOk = false;
            isOk = CheckSnInfo();
            if (isOk)
            {
                this.IsFocusTestValue1 = false;
                this.IsFocusTestValue1 = true;
                this.IsFocusTestValue2 = false;
                this.IsFocusSn = false;
            }
            else
                this.IsFocusSn = true;
        }
        /// <summary>
        /// 测试值回车事件处理
        /// </summary>
        private void SpecKeyEnterHandler()
        {
            bool isOk = false;
            isOk = CheckTestValue(TestValue1);
            if (isOk)
            {
                if (IsVisibilityTestValue2 == Visibility.Visible)
                {
                    this.IsFocusTestValue2 = false;
                    this.IsFocusTestValue1 = false;
                    this.IsFocusTestValue2 = true;
                }
                else
                {
                    this.IsFocusTestValue1 = false;
                    Entry();//提交数据
                }
            }
            else
            {
                this.IsFocusTestValue1 = true;
            }
        }
        /// <summary>
        /// 测试值2回车事件处理
        /// </summary>
        private void Spec2KeyEnterHandler()
        {
            bool isOk = false;
            isOk = CheckTestValue(TestValue2);
            if (isOk)
            {
                this.IsFocusTestValue2 = false;
              Entry();//提交数据
            }
            else
            {
                this.IsFocusTestValue2 = true;
            }
        }


        /// <summary>
        /// 检查录入的序列号信息
        /// </summary>
        /// <returns></returns>
        private bool CheckSnInfo()
        {
            string pn = string.Empty;//机种
            if (string.IsNullOrEmpty(this.SN))
            {
                MessageBox.Show("序列号信息不能为空,请输入序列号信息.", "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }
            if (!BusinessProcess.SNIsExists(this.SN))
            {
                MessageBox.Show("序列号【" + this.SN + "】在系统中不存在,请重新输入.", "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }
            pn = BusinessProcess.SnOwnerPN(this.SN);
            if (pn != this.PN)
            {
                MessageBox.Show("序列号【" + this.SN + "】不属于机种【" + this.PN + "】.请检查序列号信息是否正确？", "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }
            return true;
        }
        /// <summary>
        /// 检查测试值
        /// </summary>
        /// <returns></returns>
        private bool CheckTestValue(string testValue)
        {
            if (string.IsNullOrEmpty(this.TestValue1))
            {
                MessageBox.Show("测试值信息不能为空,请重新输入.", "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }
            if (!BusinessProcess.IsValidSpec(this.TestValue1))
            {
                MessageBox.Show("测试值不是有效数字,请重新输入.", "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }
            return true;
        }
        /// <summary>
        /// 添加图标数据
        /// </summary>
        void AddPieSeriesData()
        {
            List<string> titles = new List<string> { "PASS", "FAIL"};
            ChartValues<double> chartvalue = new ChartValues<double>();
            PieSeriesCollection = new SeriesCollection();
            for (int i = 0; i < titles.Count; i++)
            {
                chartvalue = new ChartValues<double>();
                PieSeries series = new PieSeries();
                if (titles[i] == "PASS")
                {
                    chartvalue.Add(passCount);
                    series.Fill = Brushes.Green;
                }
                else
                {
                    chartvalue.Add(failCount);
                    series.Fill = Brushes.Red;
                }
                series.DataLabels = true;
                series.Title = titles[i];
                series.Values = chartvalue;
                PieSeriesCollection.Add(series);
            }
        }
        #endregion
    }

}
